<template>
  <div class="app-container">
    <div class="filter-container c-flex-row c-aligni-center c-justify-sb">
      <el-form class="form-container">
        <el-input
          @keyup.enter.native="handleFilter"
          v-model="listQuery.mobile"
          clearable
          placeholder="手机号"
          class="width150"
        ></el-input>
        <el-input
          @keyup.enter.native="handleFilter"
          v-model="listQuery.nickname"
          clearable
          placeholder="昵称"
          style="width: 200px;"
        ></el-input>
        <el-date-picker
          type="date"
          :editable="false"
          @change="timeCheck(1)"
          format="yyyy-MM-dd"
          placeholder="代理时间（开始）"
          v-model="listQuery.agentSatrtTime"
        ></el-date-picker>
        <span class="c-ph20 font-s12 c-fc-xgray">到</span>
        <el-date-picker
          type="date"
          :editable="false"
          @change="timeCheck(2)"
          format="yyyy-MM-dd"
          placeholder="代理时间（结束）"
          v-model="listQuery.agentEndTime"
        ></el-date-picker>

        <el-select
          clearable
          style="width: 120px;"
          v-model="listQuery.userTypeValue"
          placeholder="身份"
          v-if="this.agentLevel > 1"
        >
          <el-option
            v-for="item in selectOptions"
            :key="item.id"
            :label="item.value"
            :value="item.id"
          ></el-option>
        </el-select>

        <el-button type="primary" icon="el-icon-search" @click="handleFilter" class="search">搜索</el-button>
      </el-form>
    </div>
    <div>
      <el-table
        :data="tableData"
        :header-row-style="{'font-family': 'PingFangSC-Semibold','backgroundColor': '#f5f7fa','color':'#5c6065'}"
        row-key="id"
        v-loading="listLoading"
        element-loading-text="加载中..."
        fit
        highlight-current-row
        style="width: 100%;font-size: 12px;color:#222;font-family: PingFangSC-Regular;"
      >
        <el-table-column width="120" align="center" label="昵称">
          <template slot-scope="scope">
            <img
              :src="scope.row.headimgurl||defultImg"
              @error="setDefultImg"
              style="width:40px;height:40px;border-radius:100%;vertical-align:middle;"
            />
            <div>{{scope.row.nickname}}</div>
            <div>{{scope.row.mobile}}</div>
            <!--<span>（ID：{{scope.row.showUserId}}）</span>-->
          </template>
        </el-table-column>
        <el-table-column width="120" align="center" label="推荐人">
          <template slot-scope="scope">
            <div v-if="scope.row.puserId">
              <!-- <img :src="scope.row.parentImg"
              style="width:40px;height:40px;border-radius:100%;vertical-align:middle;">-->
              <div>{{scope.row.reNickname}}</div>
              <div>（ID：{{scope.row.showpUserId}}）</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="代理地区/时间">
          <template slot-scope="scope">
            <span>{{scope.row.province}}{{scope.row.city}}{{scope.row.area}}</span>
            <div>{{scope.row.auditAt}}</div>
          </template>
        </el-table-column>
        <!--<el-table-column align="center" width="120" label="代理时间">-->
        <!--<template slot-scope="scope">-->
        <!--<span>{{scope.row.auditAt}}</span>-->
        <!--</template>-->
        <!--</el-table-column>-->
        <el-table-column align="center" label="直接/间接同学">
          <template slot-scope="scope">
            <span @click="myCustomer(scope.row.userId, scope.row.vipType)">
              <font
                style="text-decoration: underline;cursor: pointer;color: blue"
                title="点击查看"
              >{{scope.row.directNum}}/{{scope.row.indirectNum}}</font>
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="员工">
          <template slot-scope="scope">
            <span @click="myStaff(scope.row.userId)">
              <font
                style="text-decoration: underline;cursor: pointer;color: blue"
                title="点击查看"
              >{{scope.row.staffNum}}</font>
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="身份">
          <template slot-scope="scope">
            <span v-if="scope.row.vipType == 3">合伙人</span>
            <span v-if="scope.row.vipType == 5">事业部</span>
            <span v-if="scope.row.vipType == 6">分公司</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="赠送/剩余vip名额">
          <template slot-scope="scope">
            <span>{{scope.row.vipGivenQuota}}/{{scope.row.vipRemainingQuota}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="赠送/剩余svip名额">
          <template slot-scope="scope">
            <span>{{scope.row.svipGivenQuota}}/{{scope.row.svipRemainingQuota}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="180" label="操作" v-if="permission == 3">
          <template slot-scope="scope">
            <b class="color-409" @click="myCustomer(scope.row.userId, scope.row.vipType)">旗下客户</b>
            <b class="color-409">|</b>
            <b class="color-409" @click="myStaff(scope.row.userId)">我的员工</b>
            <el-dropdown>
              <span class="el-dropdown-link color-409">
                更多
                <i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <b
                    @click="editPartnerType(scope.row.userId, scope.$index, scope.row.showpUserId)"
                  >修改身份</b>
                </el-dropdown-item>
                <el-dropdown-item>
                  <b @click="cancelAgent(scope.row.userId, scope.$index)">取消身份</b>
                </el-dropdown-item>
                <el-dropdown-item>
                  <b @click="goPartnerManage(scope.row.userId, scope.$index)">团队/业绩管理</b>
                </el-dropdown-item>
                <el-dropdown-item>
                  <b @click="linkToGiveNum(scope.row.userId)">赠送名额</b>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

            <!-- <el-button type="primary" style="margin-left: 0" >赠送名额</el-button>
                    <el-button type="primary" style="margin-left: 0" @click="editPartnerType(scope.row.id)">修改身份</el-button>
            <el-button type="primary" style="margin-left: 0" @click="cancelAgent">取消代理</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <div class="block text-c">
        <!--分页组件 current-page:当前页   -->
        <!--   page-sizes:每页几条数据（选项）   -->
        <!--   page-size:每页几条数据   -->
        <!--   total:总条数   -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="listQuery.total"
        ></el-pagination>
      </div>
    </div>
    <editPartner
      v-if="isShowEditPartner"
      :userInfo="userInfo"
      @hideEditPartner="hideEditPartner"
      @confirmPartner="confirmPartner"
    ></editPartner>
    <myCustomers
      v-show="isShowCustomers"
      @hideCustomers="hideCustomers"
      :customerData="customerData"
    ></myCustomers>
    <myStaff v-if="isShowStaff" @hideStaff="hideStaff" :staffData="staffData"></myStaff>

    <el-dialog title="旗下客户" :visible.sync="isShowAgent">
      <el-table :data="agentList">
        <el-table-column label="会员昵称">
          <template slot-scope="scope">
            <img :src="scope.row.avaws" alt />
            <span>{{scope.row.nickname}}</span>
          </template>
        </el-table-column>
        <el-table-column property="mobile" label="手机号"></el-table-column>
        <el-table-column label="身份">
          <template slot-scope="scope">
            <span>{{scope.row.vipType == 1 ?'普通会员' :scope.row.vipType == 2 ?'VIP' :scope.row.vipType == 3 ?'代理商' :'SVIP' }}</span>
          </template>
        </el-table-column>
        <el-table-column property="relation" label="直接关系"></el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog title="赠送名额" :visible.sync="isGive">
      <el-form ref="form" :model="addNum" label-width="170px">
        <p>添加钻石VIP</p>
        <p>已用名额/剩余名额：{{giveNum.vipGivenQuota}}/{{giveNum.vipRemainingQuota}}</p>
        <el-form-item label="输入添加钻石VIP的数量:">
          <el-input-number v-model="addNum.vipNum" style="width:150px;"></el-input-number>
        </el-form-item>
        <p>添加合伙人</p>
        <p>已用名额/剩余名额：{{giveNum.agencyGivenQuota}}/{{giveNum.agencyRemainingQuota}}</p>
        <el-form-item label="输入添加合伙人的数量:">
          <el-input-number v-model="addNum.partnerNum" style="width:150px;"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="isGive = false">取 消</el-button>
        <el-button type="primary" @click="giveConfrim()">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getPartnerList,
  myCustomers,
  confirmPartner,
  cancelAgent,
  getUserInfo,
  addVipNum
} from "@/api/member";
import { marketing_partner, getAgentLevels } from "@/utils/permission";
import defultImg from "@/assets/default_head.png";
export default {
  components: {
    editPartner: require("./components/editPartner.vue").default, // 引入修改身份组件
    myCustomers: require("../member/components/myCustomers").default, // 引入旗下客户组件
    myStaff: require("./components/myStaff").default // 我的员工
  },
  data() {
    return {
      defultImg,
      addNum: {
        vipNum: "",
        partnerNum: "",
        userId: ""
      },
      isGive: false,
      permission: 3,
      listQuery: {
        userTypeValue: null,
        currentPage: 1, // 当前页
        total: null, // 数据总条数
        agentSatrtTime: null, // 搜索的代理时间（开始）
        agentEndTime: null, // 搜索的代理时间（结束）
        mobile: null, // 搜索的手机号
        nickname: null, // 搜索的姓名
        page: 1
      },
      agentLevel: 0,
      isShowEditPartner: false, // 是否显示修改身份组件
      userInfo: [],
      tableIndex: null,
      listLoading: false,
      isShowCustomers: false,
      isShowStaff: false,
      isShowAgent: false,
      tableData: [],
      staffData: { members: { data: [] } },
      customerData: {
        members: { data: [] },
        num: {
          directNum: 0,
          normalNum: 0,
          vipNum: 0,
          svipNum: 0
        }
      },
      selectOptions: [
        // 用户身份下拉菜单选择项
        {
          id: 3,
          value: "代理商"
        },
        {
          id: 5,
          value: "合伙人"
        },
        {
          id: 6,
          value: "分公司"
        }
      ],
      agentList: [],
      giveNum: {
        vipGivenQuota: null,
        vipRemainingQuota: null,
        agencyRemainingQuota: null,
        agencyGivenQuota: null
      }
    };
  },
  created() {
    this.getModelPermission();
    this.getList();
    this.agentLevel = getAgentLevels();
  },
  methods: {
    giveConfrim() {
      if (this.addNum.vipNum < 0 || this.addNum.partnerNum < 0) {
        this.$message({
          type: "warning",
          message: "添加人数不能为负数"
        });
        return;
      }
      addVipNum(this.addNum).then(res => {
        this.$message({
          type: "success",
          message: "设置成功"
        });
        this.isGive = false;
      });
    },
    goPartnerManage(id, index) {
      this.$router.push({
        path: "partnerManage",
        query: {
          id: id
        }
      });
    },
    setDefultImg(e) {
      e.target.src = defultImg;
    },
    getModelPermission() {
      this.permission = marketing_partner();
    },
    getList() {
      this.listLoading = true;
      console.log(this.listQuery);
      getPartnerList(this.listQuery)
        .then(res => {
          this.tableData = res.data.data.users.data;
          this.listQuery.total = res.data.data.users.total;
          this.listLoading = false;
        })
        .catch(err => {
          console.log(err);
        });
    },
    myCustomer(userId, vipType) {
      // 查看我的旗下客户
      this.isShowCustomers = true;
      var data = { userId: userId, vipType: vipType };
      myCustomers(data)
        .then(res => {
          this.customerData = res.data.data;
        })
        .catch(err => {
          console.log(err);
        });
    },
    hideCustomers(msg) {
      // this.customerData = []
      this.isShowCustomers = msg;
    },
    myStaff(userId) {
      this.isShowStaff = true;
      var data = { userId: userId, vipType: -1 };
      myCustomers(data)
        .then(res => {
          this.staffData = res.data.data;
        })
        .catch(err => {
          console.log(err);
        });
    },
    hideStaff(msg) {
      this.isShowStaff = msg;
    },
    linkToGiveNum(id) {
      this.addNum = {
        userId: id,
        vipNum: "",
        partnerNum: ""
      };
      getUserInfo({ userId: id }).then(res => {
        this.giveNum = {
          vipGivenQuota: res.data.data.vipGivenQuota,
          vipRemainingQuota: res.data.data.vipRemainingQuota,
          agencyRemainingQuota: res.data.data.agencyRemainingQuota,
          agencyGivenQuota: res.data.data.agencyGivenQuota
        };
      });
      // 赠送名额
      this.isGive = true;
      // this.$router.push({ path: `/marketing/partner/giveNum/${id}` });
    },
    cancelAgent(userId, index) {
      // 取消代理
      this.$confirm(
        "取消该用户代理身份，该用户身份会直接变成普通用户，他推广的用户不再归属他名下?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "再想想",
          type: "warning"
        }
      )
        .then(() => {
          var data = { userId: userId, vipType: this.vipType };
          cancelAgent(data)
            .then(res => {
              this.$message({
                type: "success",
                message: "设置成功!"
              });
              this.tableData.splice(index, 1);
            })
            .catch(err => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    editPartnerType(id, index, showId) {
      // 修改身份
      this.userInfo.userId = id;
      this.userInfo.reNickname = this.tableData[index].reNickname;
      this.userInfo.vipType = this.tableData[index].vipType;
      this.userInfo.pVipType = this.tableData[index].pVipType;
      this.userInfo.showId = showId;
      this.userInfo.agentLevel = this.agentLevel;
      this.tableIndex = index;
      this.isShowEditPartner = true;
    },
    hideEditPartner(msg) {
      // 隐藏修改身份组件
      this.isShowEditPartner = false;
      this.tableData[this.tableIndex].reNickname = msg.reNickname;
    },
    confirmPartner(res) {
      this.tableData[this.tableIndex].reNickname = res.reNickname;
      var data = {
        userId: this.userInfo.userId,
        parentId: res.showId,
        vipType: res.vipType
      };
      confirmPartner(data)
        .then(json => {
          if (json.data.statusCode == 200) {
            this.$message({
              type: "success",
              message: "修改成功!"
            });
            // this.tableData[this.tableIndex].vipType = res.vipType
            this.getList();
            this.isShowCommand = false;
          }
        })
        .catch(err => {
          console.log(err);
        });

      this.isShowEditPartner = false;
    },
    handleSizeChange(val) {
      // 切换每页几条数据方法
      // console.log(`每页 ${val} 条`)
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      // 切换当前页
      // console.log(`当前页: ${val}`)
      this.listQuery.page = val;
      this.getList();
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    timeCheck(type) {
      if (
        this.listQuery.agent_time &&
        this.listQuery.end_time &&
        this.listQuery.agent_time > this.listQuery.end_time
      ) {
        this.$message({
          message: "结束时间不能小于开始时间",
          type: "error"
        });

        if (type == 1) {
          this.listQuery.agent_time = null;
        } else {
          this.listQuery.end_time = null;
        }
      }
    }
  },
  mounted() {
    this.listQuery.total = this.tableData.length;
  }
};
</script>

<style scoped>
b {
  font-weight: 500;
  cursor: pointer;
  padding: 0 5px;
}

b:hover {
  color: #0a76a4;
}
</style>
